import React, { useState, useEffect } from 'react';
import './AttendancePage.css';
import AttendanceTable from './components/AttendanceTable';
import AddEditAttendanceModal from './components/AddEditAttendanceModal';
import ConfirmModal from './components/ConfirmModal';
import AttendanceDetailModal from './components/AttendanceDetailModal';
import { Attendance, initialAttendances, statusOptions, studentOptions, classOptions } from './types';

const AttendancePage: React.FC = () => {
  const [attendances, setAttendances] = useState<Attendance[]>([]);
  const [filteredAttendances, setFilteredAttendances] = useState<Attendance[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedClass, setSelectedClass] = useState('');
  const [selectedStatus, setSelectedStatus] = useState('');
  const [selectedDate, setSelectedDate] = useState('');
  const [showAddEditModal, setShowAddEditModal] = useState(false);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [showDetailModal, setShowDetailModal] = useState(false);
  const [selectedAttendance, setSelectedAttendance] = useState<Attendance | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const itemsPerPageOptions = [5, 10, 20, 50]; // 每页显示条数选项

  // 计算总页数
  const totalPages = Math.ceil(filteredAttendances.length / itemsPerPage);

  // 处理每页显示条数变化
  const handleItemsPerPageChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setItemsPerPage(parseInt(e.target.value, 10));
    setCurrentPage(1); // 重置到第一页
  };

  // 跳转到指定页码
  const handlePageJump = (pageNum: number) => {
    if (pageNum >= 1 && pageNum <= totalPages) {
      setCurrentPage(pageNum);
    }
  };

  // 快速跳转到首页或末页
  const goToFirstPage = () => setCurrentPage(1);
  const goToLastPage = () => setCurrentPage(totalPages);

  // 初始化考勤数据 - 从localStorage读取或使用初始数据
  useEffect(() => {
    const savedAttendances = localStorage.getItem('attendances');
    if (savedAttendances) {
      const parsedAttendances = JSON.parse(savedAttendances);
      setAttendances(parsedAttendances);
      setFilteredAttendances(parsedAttendances);
    } else {
      // 首次加载时，将初始数据保存到localStorage
      setAttendances(initialAttendances);
      setFilteredAttendances(initialAttendances);
      localStorage.setItem('attendances', JSON.stringify(initialAttendances));
    }
  }, []);

  // 当考勤数据变化时，更新localStorage
  useEffect(() => {
    if (attendances.length > 0) { // 确保不是初始的空数组状态
      localStorage.setItem('attendances', JSON.stringify(attendances));
    }
  }, [attendances]);

  // 过滤考勤数据
  useEffect(() => {
    let result = [...attendances];

    // 按学生姓名、学号搜索
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      result = result.filter(
        attendance =>
          attendance.studentName.toLowerCase().includes(term) ||
          attendance.studentId.toLowerCase().includes(term)
      );
    }

    // 按班级过滤
    if (selectedClass) {
      result = result.filter(attendance => attendance.classId === selectedClass);
    }

    // 按状态过滤
    if (selectedStatus) {
      result = result.filter(attendance => attendance.status === selectedStatus);
    }

    // 按日期过滤
    if (selectedDate) {
      result = result.filter(attendance => attendance.date === selectedDate);
    }

    // 按日期降序排序
    result.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());

    setFilteredAttendances(result);
    setCurrentPage(1); // 重置到第一页
  }, [attendances, searchTerm, selectedClass, selectedStatus, selectedDate]);

  // 分页逻辑
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentAttendances = filteredAttendances.slice(indexOfFirstItem, indexOfLastItem);

  // 处理查看考勤详情
  const handleViewDetail = (attendance: Attendance) => {
    setSelectedAttendance(attendance);
    setShowDetailModal(true);
  };

  // 处理添加考勤记录
  const handleAddAttendance = () => {
    setSelectedAttendance(null);
    setIsEditing(false);
    setShowAddEditModal(true);
  };

  // 处理编辑考勤记录
  const handleEditAttendance = (attendance: Attendance) => {
    setSelectedAttendance(attendance);
    setIsEditing(true);
    setShowAddEditModal(true);
  };

  // 处理删除考勤记录
  const handleDeleteAttendance = (attendance: Attendance) => {
    setSelectedAttendance(attendance);
    setShowConfirmModal(true);
  };

  // 确认删除考勤记录
  const confirmDeleteAttendance = () => {
    if (selectedAttendance) {
      setAttendances(attendances.filter(att => att.id !== selectedAttendance.id));
      setShowConfirmModal(false);
      setSelectedAttendance(null);
    }
  };

  // 保存考勤信息（添加或编辑）
  const handleSaveAttendance = (attendanceData: Attendance) => {
    if (isEditing && selectedAttendance) {
      // 编辑现有考勤记录
      setAttendances(attendances.map(att => 
        att.id === selectedAttendance.id ? attendanceData : att
      ));
    } else {
      // 添加新考勤记录
      setAttendances([...attendances, attendanceData]);
    }
    setShowAddEditModal(false);
    setSelectedAttendance(null);
  };

  // 生成页码数组
  const generatePageNumbers = () => {
    const pages = [];
    const maxVisiblePages = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

    if (endPage - startPage + 1 < maxVisiblePages) {
      startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

    for (let i = startPage; i <= endPage; i++) {
      pages.push(i);
    }
    return pages;
  };

  // 计算统计数据
  const calculateStatistics = () => {
    const total = filteredAttendances.length;
    if (total === 0) return { total, present: 0, absent: 0, late: 0, presentRate: 0 };
    
    const present = filteredAttendances.filter(att => att.status === 'present').length;
    const absent = filteredAttendances.filter(att => att.status === 'absent').length;
    const late = filteredAttendances.filter(att => att.status === 'late').length;
    const presentRate = Math.round((present / total) * 100);
    
    return { total, present, absent, late, presentRate };
  };

  const stats = calculateStatistics();

  return (
    <div className="attendance-management-container">
      <div className="page-header">
        <h1>考勤管理</h1>
        <div className="header-actions">
          <button className="add-attendance-btn" onClick={handleAddAttendance}>
            添加考勤记录
          </button>
        </div>
      </div>

      <div className="statistics-cards">
        <div className="stat-card">
          <div className="stat-value">{stats.total}</div>
          <div className="stat-label">总记录数</div>
        </div>
        <div className="stat-card present">
          <div className="stat-value">{stats.present}</div>
          <div className="stat-label">出勤</div>
        </div>
        <div className="stat-card absent">
          <div className="stat-value">{stats.absent}</div>
          <div className="stat-label">缺勤</div>
        </div>
        <div className="stat-card late">
          <div className="stat-value">{stats.late}</div>
          <div className="stat-label">迟到</div>
        </div>
        <div className="stat-card rate">
          <div className="stat-value">{stats.presentRate}%</div>
          <div className="stat-label">出勤率</div>
        </div>
      </div>

      <div className="filter-section">
        <div className="search-box">
          <input
            type="text"
            placeholder="搜索学生姓名或学号..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>
        <div className="filter-controls">
          <select
            value={selectedClass}
            onChange={(e) => setSelectedClass(e.target.value)}
          >
            <option value="">所有班级</option>
            {classOptions.map(option => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
          <select
            value={selectedStatus}
            onChange={(e) => setSelectedStatus(e.target.value)}
          >
            <option value="">所有状态</option>
            {statusOptions.map(option => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
          <input
            type="date"
            value={selectedDate}
            onChange={(e) => setSelectedDate(e.target.value)}
            placeholder="选择日期"
          />
        </div>
      </div>

      <div className="attendance-table-container">
        <AttendanceTable
          attendances={currentAttendances}
          onViewDetail={handleViewDetail}
          onEdit={handleEditAttendance}
          onDelete={handleDeleteAttendance}
        />
      </div>

      <div className="pagination-section">
        <div className="pagination-info">
          显示第 {indexOfFirstItem + 1} 到 {Math.min(indexOfLastItem, filteredAttendances.length)} 条，共 {filteredAttendances.length} 条记录
        </div>
        <div className="pagination-controls">
          <select
            value={itemsPerPage}
            onChange={handleItemsPerPageChange}
            className="items-per-page-select"
          >
            {itemsPerPageOptions.map(option => (
              <option key={option} value={option}>
                每页 {option} 条
              </option>
            ))}
          </select>
          <div className="page-buttons">
            <button
              onClick={goToFirstPage}
              disabled={currentPage === 1}
              className="page-btn"
            >
              首页
            </button>
            <button
              onClick={() => handlePageJump(currentPage - 1)}
              disabled={currentPage === 1}
              className="page-btn"
            >
              上一页
            </button>
            {generatePageNumbers().map(page => (
              <button
                key={page}
                onClick={() => handlePageJump(page)}
                className={`page-btn ${currentPage === page ? 'active' : ''}`}
              >
                {page}
              </button>
            ))}
            <button
              onClick={() => handlePageJump(currentPage + 1)}
              disabled={currentPage === totalPages}
              className="page-btn"
            >
              下一页
            </button>
            <button
              onClick={goToLastPage}
              disabled={currentPage === totalPages}
              className="page-btn"
            >
              末页
            </button>
          </div>
        </div>
      </div>

      {/* 添加/编辑考勤模态框 */}
      <AddEditAttendanceModal
        isOpen={showAddEditModal}
        onClose={() => setShowAddEditModal(false)}
        onSave={handleSaveAttendance}
        initialData={selectedAttendance}
        isEditing={isEditing}
      />

      {/* 确认删除模态框 */}
      <ConfirmModal
        isOpen={showConfirmModal}
        onClose={() => setShowConfirmModal(false)}
        onConfirm={confirmDeleteAttendance}
        title="确认删除"
        message={`确定要删除 ${selectedAttendance?.studentName} 的考勤记录吗？此操作不可撤销。`}
      />

      {/* 考勤详情模态框 */}
      <AttendanceDetailModal
        isOpen={showDetailModal}
        onClose={() => setShowDetailModal(false)}
        attendanceData={selectedAttendance}
      />
    </div>
  );
};

export default AttendancePage;